#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];

char *const container_args[] = {
    "/bin/bash",
    NULL};

int container_main(void *arg)
{
    printf("Container - 进入容器!\n");
    // 打印当前进程的PID,会看到进程id是1。
    printf("子进程PID [%5d] \n", getpid());
    sethostname("yunsheng", 8);
    /* 重新mount proc文件系统到 /proc下 */
    system("mount -t proc proc /proc");
    execv(container_args[0], container_args);
    printf("Something's wrong!\n");
    return 1;
}

int main()
{
    printf("Parent父进程 - start a container!\n");
    printf("父进程PID [%5d] \n", getpid());
    int container_pid = clone(container_main, container_stack + STACK_SIZE, CLONE_NEWNET | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);

    printf("Parent [%5d] - Container进程号： [%5d]!\n", getpid(), container_pid);
    
    waitpid(container_pid, NULL, 0);
    printf("Parent - container stopped!\n");
    return 0;
}